package com.pft.web.view.presenter;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.pft.web.BuildConfig;
import com.pft.web.util.IntentUtils;
import com.pft.web.util.UpgradeManager;
import com.pft.web.util.Utils;
import com.pft.web.view.contract.WebViewContract;

public class WebViewPresenterImp
        implements WebViewContract.Presenter {
    private boolean isLoadSuccessed;
    private ValueCallback<Uri[]> mFilePathCallback;
    private WebViewContract.View mView;
    private boolean needClearHistory;

    public WebViewPresenterImp(WebViewContract.View paramView) {
        this.mView = paramView;
    }

    @Override
    public void setupWebView(final WebView webView) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextZoom(100);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        addJSObject(webView);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                webView.getContext().startActivity(IntentUtils.getChooserIntent(IntentUtils.getViewIntent(url), "请选择将要打开的应用"));
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {


            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (Build.VERSION.SDK_INT >= 21) {
                    mFilePathCallback = filePathCallback;
                    mView.showFilePickerPage(fileChooserParams.createIntent());
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mView.showLoadProgress(newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                mView.showTitle(title);
            }

        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                if (needClearHistory) {
                    needClearHistory = false;
                    view.clearHistory();
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mView.showLoadProgress(0);

                mView.showSuccessView();
                isLoadSuccessed = true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                mView.showLoadProgress(100);
                mView.showTitle(view.getTitle());

                if (isLoadSuccessed) {
                    mView.showSuccessView();
                }

                if (view.canGoBack()) {
                    mView.setCloseVisibility(View.VISIBLE);
                } else {
                    mView.setCloseVisibility(View.GONE);
                }
            }

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                mView.showFailedView();
                isLoadSuccessed = false;
            }

            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return interceptUrlLoading(view, url);
            }
        });
    }


    private void addJSObject(WebView webView) {
        webView.addJavascriptInterface(new JSInterfaceImp(), "Android");
    }

    private boolean interceptUrlLoading(WebView view, String url) {
        boolean intercepted = false;

        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            switch (uri.getScheme()) {
                case "tel": {
                    mView.showCallphonePage(Uri.parse(url));
                    intercepted = true;
                    break;
                }
                default:
                    break;
            }
        }
        return intercepted;
    }


    private void invokeJSInterface(final WebView webView, String method, Object... params) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("javascript:").append(method);
        stringBuilder.append('(');
        if (params != null) {
            String separator = "";
            for (Object param : params) {
                stringBuilder.append(separator);
                separator = ",";
                if (param instanceof String) {
                    stringBuilder.append('\'');
                }
                stringBuilder.append(param);
                if (param instanceof String) {
                    stringBuilder.append('\'');
                }
            }
        }
        stringBuilder.append(')');
        final String url = stringBuilder.toString();
        webView.post(new Runnable() {
            @Override
            public void run() {
                loadUrl(webView, url);
            }
        });
    }


    private void loadUrl(WebView paramWebView, String url) {
        paramWebView.loadUrl(url);
    }


    private void webGoBack(WebView paramWebView) {
        if (paramWebView.canGoBack()) {
            paramWebView.goBack();
            return;
        }
        this.mView.closeWebContainer();
    }

    public void destroy() {
    }


    @Override
    public void gainFilePicker(int resultCode, Intent intent) {
        if (Build.VERSION.SDK_INT >= 21) {
            if (intent == null) {
                mFilePathCallback.onReceiveValue(null);
            } else {
                mFilePathCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
            }
        }
    }


    @Override
    public void gainScanQrCode(WebView webView, int resultCode, String data) {
        invokeJSInterface(webView, "qrCodeResult", new Object[]{Integer.valueOf(resultCode), data});
    }

    @Override
    public void gainGps(int state, double lat, double lng) {
        invokeJSInterface(mView.getWebView(), "setGps", new Object[]{Integer.valueOf(state), lat, lng});
    }

    public void goBack(WebView paramWebView) {
        invokeJSInterface(paramWebView, "AndroidBack", new Object[0]);
    }

    private void invokeAppVersion(WebView paramWebView, int state, String data) {
        invokeJSInterface(paramWebView, "appVersion", new Object[]{Integer.valueOf(state), data});
    }

    public void loadStartUrl(WebView paramWebView, String paramString) {
        paramWebView.loadUrl(paramString);
    }

    public void reloadUrl(WebView paramWebView) {
        paramWebView.reload();
    }

    private class JSInterfaceImp {
        private JSInterfaceImp() {
        }

        @JavascriptInterface
        public void closeApp() {
            WebViewPresenterImp.this.mView.closeWebContainer();
        }

        @JavascriptInterface
        public void goBack() {
            WebViewPresenterImp.this.webGoBack(mView.getWebView());
        }

        @JavascriptInterface
        public void scanQrCode() {
            WebViewPresenterImp.this.mView.showScanQrCode();
        }

        @JavascriptInterface
        public void appVersion() {
            invokeAppVersion(mView.getWebView(), 1, BuildConfig.VERSION_NAME);
        }

        @JavascriptInterface
        public void updateApp(String url) {
            UpgradeManager.upgradeForDownloadManager(Utils.getContext(), url);
        }

        @JavascriptInterface
        public void getGps() {
            WebViewPresenterImp.this.mView.startLocation();
        }

        @JavascriptInterface
        public void bluetoothPrint(String data) {
            if (TextUtils.isEmpty(data)) return;
            WebViewPresenterImp.this.mView.bluetoothPrint(data);
        }

        @JavascriptInterface
        public void clearMemory() {
            needClearHistory = true;
            mView.clearMemory();

            // 清除cookie即可彻底清除缓存

        }
    }
}
